<?php

namespace App\Models;

use App\Events\UserLearnVideoChangeEvent;
use Arr;
use Auth;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class LearnVideo extends BaseModel
{
    protected $guarded = [];

    protected $appends = ['userWatchSectionCount', 'userWatchSectionRate', 'userHas', 'userBuyLog', 'getTypeText', 'statusText'];

    public function learnVideoChapter(): HasMany
    {
        return $this->hasMany(LearnVideoChapter::class, 'learn_video_id');
    }

    public function learnVideoSection(): HasMany
    {
        return $this->hasMany(LearnVideoSection::class, 'learn_video_id');
    }


    /**
     * 观看的小节数量
     * @return int|mixed
     */
    public function getUserWatchSectionCountAttribute()
    {
        if (Auth::guard('api')->check()) {
            $user = Auth::guard('api')->user();
            $log = DB::table('user_learn_video_logs')->where('userId', $user->id)->where('learnVideoId', $this->id)->first();
            if (!$log) return 0;
            return $log->watchSectionCount;
        }
        return 0;
    }

    /**
     * 获取记录
     * @return array|null
     */
    public function getUserBuyLogAttribute(): ?array
    {
        $log = null;
        if (Auth::guard('api')->check() && request()->is('api/*')) {
            $log = DB::table('user_learn_video_logs')->where('userId', Auth::guard('api')->user()->id)->where('learnVideoId', $this->id)->first();
            if ($log) {
                // 有记录-未过期
                if (Carbon::make($log->expireAt??now()->subMinutes(10))->gt(now())) {
                    $log->useHas = true;
                }

                // 有记录-已过期
                if (Carbon::make($log->expireAt??now()->subMinutes(10))->lt(now())) {
                    // 有记录-已过期-收费中
                    if ($this->price > 0) {
                        $log->useHas = false;
                        if ($log->isTry == 1) {
                            DB::table('user_learn_video_logs')->where('id', $log->id)->update(['isTry' => 0]);
                            event(new UserLearnVideoChangeEvent(Auth::guard('api')->user()->id));
                        }
                    }
                    // 有记录-已过期-限免中
                    else {
                        $log->useHas = true;
                        if ($log->isTry == 0) {
                            DB::table('user_learn_video_logs')->where('id', $log->id)->update(['isTry' => 1]);
                            event(new UserLearnVideoChangeEvent(Auth::guard('api')->user()->id));
                        }
                        $log->isTry = 1;
                    }
                }
                $log->data = $log->data ? (is_string($log->data) ? json_decode($log->data, true) : $log->data) : [];
            }else {
                if ($this->price <= 0 && request()->is('api/qh_mp/netCourse/getLearnVideoInfo')) {
                    $logId = DB::table('user_learn_video_logs')->insertGetId([
                        'userId' => Auth::guard('api')->user()->id,
                        'learnVideoId' => $this->id,
                        'getType' => 3, // 限免
                        'isTry' => 1,
                        'getAt' => now(),
                        'expireAt' => now()
                    ]);
                    $log = DB::table('user_learn_video_logs')->find($logId);

                    event(new UserLearnVideoChangeEvent(Auth::guard('api')->user()->id));

                    $log->useHas = true;
                    $log->data = $log->data ? (is_string($log->data) ? json_decode($log->data, true) : $log->data) : [];
                    $this->real_learn_count += 1;
                    $this->learn_count += 1;
                    $this->save();
                }
            }
        }

        if ($log) {
            $log = [
                'id' => $log->id,
                'getType' => $log->getType,
                'isTry' => $log->isTry,
                'useHas' => $log->useHas,
                'getAt' => $log->getAt,
                'data' => $log->data ? (is_string($log->data) ? json_decode($log->data, true) : $log->data) : [],
                'expireAt' => $log->expireAt ? (Carbon::make($log->expireAt)->diffInYears(now()) > 90 ? '长期' : Carbon::make($log->expireAt)->format('Y.m.d')) : now()->format('Y.m.d'),
                'lastWatchSection' => LearnVideoSection::find($log->lastWatchLearnVideoSectionId)
            ];
        }

        return $log;
    }

    public function getUserHasAttribute(): bool
    {
        if (Auth::guard('api')->check() && request()->is('api/*')) {
            return !empty($this->userBuyLog) && ($this->userBuyLog['useHas']);
        }

        return false;
    }

    /**
     * 观看进度
     * @return float|int
     */
    public function getUserWatchSectionRateAttribute()
    {
        //if (Auth::guard('api')->check() && request()->is('api/*')) {
        //    if (!empty($this->userBuyLog)) {
        //        $watchSections = 0;
        //        $logData = !empty($this->userBuyLog['data']) ? $this->userBuyLog['data'] : [];
        //        foreach ($logData as $datum) {
        //            $watchSections += count($datum['sections']);
        //        }
        //        $rate = $this->section_count > 0 && $watchSections > 0 ? ($watchSections / $this->section_count) * 100 : 0;
        //    }
        //}
        //
        //return 0;

        return $this->section_count <= 0 || $this->userWatchSectionCount <= 0 ? 0 : round(($this->userWatchSectionCount / $this->section_count) * 100, 2);
    }

    public function getGetTypeTextAttribute()
    {
        if (!empty($this->getType)) {
            switch ($this->getType) {
                case 1:
                    return '购买';
                case 2:
                    return '激活码';
                case 3:
                    return '限免';
                case 5:
                    return '专栏激活';
                case 6:
                    return '专栏购买';
                case 4:
                default:
                    return '其他';
            }
        }
        return null;
    }

    public function getStatusTextAttribute()
    {
        if (!empty($this->expireAt)) {
            if (Carbon::make($this->expireAt)->isBefore(now())) return '已过期';
            else return '生效中';
        }
        return null;
    }
}
